#!/usr/bin/env python3

"""
Combined example of edge_tts usage with HTTP server.
"""

import asyncio
import subprocess
import threading
from http.server import HTTPServer, BaseHTTPRequestHandler

import edge_tts


class RequestHandler(BaseHTTPRequestHandler):
    def do_POST(self):
        # 只接受Content-Type为"text/plain"的请求
        if self.headers.get('Content-Type') == 'text/plain':
            # 获取content length
            content_length = int(self.headers.get('Content-Length', 0))
            # 读取请求的正文数据
            post_data = self.rfile.read(content_length).decode('utf-8')

            # 打印请求的正文数据
            print(post_data)

            # 发送应答
            self.send_response(200)
            self.end_headers()
            self.wfile.write(b"Received and processed text")
            # 在后台处理TTS
            threading.Thread(target=self.handle_tts, args=(post_data,)).start()
        else:
            # 如果Content-Type不是"text/plain"，返回415 Unsupported Media Type
            self.send_response(415)
            self.end_headers()
            self.wfile.write(b"Unsupported Media Type. Only 'text/plain' is supported.")

    def handle_tts(self, text):
        """Handles TTS conversion in a separate thread."""
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        loop.run_until_complete(amain(text))
        loop.close()


VOICE = "zh-CN-YunyangNeural"
OUTPUT_FILE = "test.mp3"


async def amain(text) -> None:
    """Main function to convert text to speech and play it."""
    communicate = edge_tts.Communicate(text, VOICE)
    await communicate.save(OUTPUT_FILE)
    # 播放生成的MP3文件
    with subprocess.Popen(["mpv", OUTPUT_FILE]) as process:
        process.communicate()


if __name__ == "__main__":
    # 设置HTTP服务器
    server_address = ('', 19999)
    httpd = HTTPServer(server_address, RequestHandler)
    print('Running server on port 19999...')
    httpd.serve_forever()
